# -*- coding: utf-8 -*-

import json
import logging
from odoo import http, fields
from odoo.http import request
from odoo.exceptions import UserError, ValidationError
from .api_base import APIBaseController

_logger = logging.getLogger(__name__)


class DepartmentController(APIBaseController):
    """部门管理控制器"""



    @http.route('/api/system/dept/list', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def dept_list(self, **kwargs):
        """部门列表查询"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:dept:list'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs or {}
            
            # 构建查询条件
            domain = []
            
            # 部门名称查询
            if data.get('deptName'):
                domain.append(('name', 'ilike', data['deptName']))
            
            # 状态查询
            if 'status' in data:
                domain.append(('status', '=', data['status'] == '0'))
            
            # 查询部门
            departments = request.env['device.department'].sudo().search(domain, order='sequence, name')
            
            # 构建树形结构
            def build_tree(parent_id=None):
                children = []
                for dept in departments.filtered(lambda x: x.parent_id.id == (parent_id or False)):
                    dept_data = {
                        'deptId': dept.id,
                        'parentId': dept.parent_id.id if dept.parent_id else 0,
                        'ancestors': '',  # 祖级列表
                        'deptName': dept.name,
                        'orderNum': dept.sequence,
                        'leader': dept.leader_id.name if dept.leader_id else '',
                        'phone': dept.phone,
                        'email': dept.email,
                        'status': '0' if dept.status else '1',
                        'delFlag': '0',
                        'createTime': dept.create_time and dept.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                        'children': build_tree(dept.id)
                    }
                    children.append(dept_data)
                return children
            
            tree_data = build_tree()
            
            return {
                'code': 200,
                'msg': '查询成功',
                'data': tree_data
            }
            
        except Exception as e:
            _logger.error(f"查询部门列表异常: {str(e)}")
            return {'code': 500, 'msg': f'查询失败: {str(e)}', 'data': None}

    @http.route('/api/system/dept', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def dept_add(self, **kwargs):
        """新增部门"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:dept:add'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs
            
            # 验证必填字段
            if not data.get('deptName'):
                return {'code': 500, 'msg': '部门名称不能为空', 'data': None}
            
            # 检查部门编码是否已存在
            if data.get('deptCode'):
                existing_dept = request.env['device.department'].sudo().search([
                    ('code', '=', data['deptCode'])
                ], limit=1)
                if existing_dept:
                    return {'code': 500, 'msg': '部门编码已存在', 'data': None}
            
            # 创建部门
            dept_vals = {
                'name': data['deptName'],
                'code': data.get('deptCode', data['deptName']),
                'sequence': data.get('orderNum', 10),
                'phone': data.get('phone'),
                'email': data.get('email'),
                'status': data.get('status', '0') == '0',
                'create_by': current_user.id
            }
            
            # 父部门
            if data.get('parentId') and data['parentId'] != 0:
                dept_vals['parent_id'] = data['parentId']
            
            # 负责人
            if data.get('leader'):
                leader = request.env['res.users'].sudo().search([
                    ('name', '=', data['leader'])
                ], limit=1)
                if leader:
                    dept_vals['leader_id'] = leader.id
            
            new_dept = request.env['device.department'].sudo().create(dept_vals)
            
            return {'code': 200, 'msg': '新增成功', 'data': None}
            
        except Exception as e:
            _logger.error(f"新增部门异常: {str(e)}")
            return {'code': 500, 'msg': f'新增失败: {str(e)}', 'data': None}

    @http.route('/api/system/dept/<int:dept_id>', type='json', auth='none', methods=['PUT'], csrf=False, cors='*')
    def dept_edit(self, dept_id, **kwargs):
        """修改部门"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:dept:edit'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs
            
            # 查找部门
            dept = request.env['device.department'].sudo().browse(dept_id)
            if not dept.exists():
                return {'code': 500, 'msg': '部门不存在', 'data': None}
            
            # 检查部门编码是否已被其他部门使用
            if data.get('deptCode') and data['deptCode'] != dept.code:
                existing_dept = request.env['device.department'].sudo().search([
                    ('code', '=', data['deptCode']),
                    ('id', '!=', dept_id)
                ], limit=1)
                if existing_dept:
                    return {'code': 500, 'msg': '部门编码已存在', 'data': None}
            
            # 更新部门信息
            dept_vals = {
                'update_by': current_user.id
            }
            
            if data.get('deptName'):
                dept_vals['name'] = data['deptName']
            if data.get('deptCode'):
                dept_vals['code'] = data['deptCode']
            if 'orderNum' in data:
                dept_vals['sequence'] = data['orderNum']
            if 'phone' in data:
                dept_vals['phone'] = data['phone']
            if 'email' in data:
                dept_vals['email'] = data['email']
            if 'status' in data:
                dept_vals['status'] = data['status'] == '0'
            
            # 父部门
            if 'parentId' in data:
                if data['parentId'] and data['parentId'] != 0:
                    # 检查是否会形成循环引用
                    if data['parentId'] == dept_id:
                        return {'code': 500, 'msg': '上级部门不能选择自己', 'data': None}
                    
                    # 检查是否选择了自己的子部门作为父部门
                    child_depts = dept.get_children_departments()
                    if data['parentId'] in child_depts.ids:
                        return {'code': 500, 'msg': '上级部门不能选择自己的子部门', 'data': None}
                    
                    dept_vals['parent_id'] = data['parentId']
                else:
                    dept_vals['parent_id'] = False
            
            # 负责人
            if 'leader' in data:
                if data['leader']:
                    leader = request.env['res.users'].sudo().search([
                        ('name', '=', data['leader'])
                    ], limit=1)
                    if leader:
                        dept_vals['leader_id'] = leader.id
                    else:
                        dept_vals['leader_id'] = False
                else:
                    dept_vals['leader_id'] = False
            
            dept.sudo().write(dept_vals)
            
            return {'code': 200, 'msg': '修改成功', 'data': None}
            
        except Exception as e:
            _logger.error(f"修改部门异常: {str(e)}")
            return {'code': 500, 'msg': f'修改失败: {str(e)}', 'data': None}

    @http.route('/api/system/dept/<int:dept_id>', type='json', auth='none', methods=['DELETE'], csrf=False, cors='*')
    def dept_delete(self, dept_id, **kwargs):
        """删除部门"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:dept:remove'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            # 查找部门
            dept = request.env['device.department'].sudo().browse(dept_id)
            if not dept.exists():
                return {'code': 500, 'msg': '部门不存在', 'data': None}
            
            # 检查是否有子部门
            if dept.child_ids:
                return {'code': 500, 'msg': '存在下级部门，不允许删除', 'data': None}
            
            # 检查是否有用户
            user_count = request.env['res.users'].sudo().search_count([
                ('department_id', '=', dept_id),
                ('del_flag', '=', '0')
            ])
            if user_count > 0:
                return {'code': 500, 'msg': '部门存在用户，不允许删除', 'data': None}
            
            # 删除部门
            dept.sudo().unlink()
            
            return {'code': 200, 'msg': '删除成功', 'data': None}
            
        except Exception as e:
            _logger.error(f"删除部门异常: {str(e)}")
            return {'code': 500, 'msg': f'删除失败: {str(e)}', 'data': None}

    @http.route('/api/system/dept/treeselect', type='json', auth='none', methods=['GET', 'POST'], csrf=False, cors='*')
    def dept_tree_select(self, **kwargs):
        """获取部门下拉树列表"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 查询所有部门
            departments = request.env['device.department'].sudo().search([], order='sequence, name')
            
            # 构建树形结构
            def build_tree_select(parent_id=None):
                children = []
                for dept in departments.filtered(lambda x: x.parent_id.id == (parent_id or False)):
                    tree_data = {
                        'id': dept.id,
                        'label': dept.name,
                        'children': build_tree_select(dept.id)
                    }
                    children.append(tree_data)
                return children
            
            tree_data = build_tree_select()
            
            return {
                'code': 200,
                'msg': '查询成功',
                'data': tree_data
            }
            
        except Exception as e:
            _logger.error(f"获取部门树异常: {str(e)}")
            return {'code': 500, 'msg': f'查询失败: {str(e)}', 'data': None}

    @http.route('/api/system/dept/roleDeptTreeselect/<int:role_id>', type='json', auth='none', methods=['GET'], csrf=False, cors='*')
    def role_dept_tree_select(self, role_id, **kwargs):
        """加载对应角色部门列表树"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 查询所有部门
            departments = request.env['device.department'].sudo().search([], order='sequence, name')
            
            # 构建树形结构
            def build_tree_select(parent_id=None):
                children = []
                for dept in departments.filtered(lambda x: x.parent_id.id == (parent_id or False)):
                    tree_data = {
                        'id': dept.id,
                        'label': dept.name,
                        'children': build_tree_select(dept.id)
                    }
                    children.append(tree_data)
                return children
            
            tree_data = build_tree_select()
            
            # 获取角色已选择的部门ID
            role = request.env['device.user.role'].sudo().browse(role_id)
            checked_keys = role.department_ids.ids if role.exists() else []
            
            return {
                'code': 200,
                'msg': '查询成功',
                'data': {
                    'depts': tree_data,
                    'checkedKeys': checked_keys
                }
            }
            
        except Exception as e:
            _logger.error(f"获取角色部门树异常: {str(e)}")
            return {'code': 500, 'msg': f'查询失败: {str(e)}', 'data': None}
